package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: haitao
 * @email: haitaoss@aliyun.com
 * @date: 2020/7/18 16:30:04
 * @Description
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                System.out.println("RequestInterceptor...." + Thread.currentThread().getId());

                //1、RequestContextHolder拿到同一线程里面的request（这是spring为了简化我们的操作提供的，当然你可以直接从handler方法里面获取HttpServletRequest）
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();// 老请求
                    // 同步请求头数据，Cookie
                    String cookie = request.getHeader("Cookie");
                    // 给请求同步老请求的cookie信息
                    template.header("Cookie", cookie);
                }

            }
        };
    }
}
